<?php
/**
 * @author Demianchuk Dmitro
 * @email d.demianchuk@gmail.com
 * @date 09.01.12
 * @version 1.0
 * @package adminArea
 */
class EnumInput extends EditorComponent
{
	/**
	 * @param CActiveRecord $model
	 * @return CActiveRecord
	 */
	public function save($model){
		if(isset($_POST['_formNull'][$this->name]) && $_POST['_formNull'][$this->name]=='on' && $this->allowNull()){
			$name = $this->name;
			$model->$name = null;
			return $model;
		}
		if(isset($_POST['_form'][$this->name])){
			$name = $this->name;
			$model->$name = $_POST['_form'][$this->name];
		}
		return $model;
	}

	/**
	 * @return string
	 */
	public function show(){
		$dbType = $this->model->getTableSchema()->columns[$this->name]->dbType;
		if(substr($dbType,0,4)=='enum'){
			$enumList = substr($dbType,6);
			$enumList = substr($enumList,0,-2);
			$enumList = explode("','",$enumList);
			$inputList = '';
			$name = $this->name;
			if(ATableEditor::isNewRecord() && !$this->allowNull()){
				$isNull = false;
			}else{
				$isNull = true;
			}
			foreach($enumList as $v){
				if(!$isNull || (!ATableEditor::isNewRecord() && $this->current->$name==$v)){
					$isNull = true;
					$value = 'checked="checked"';
				}else{
					$value = '';
				}
				$inputList .= <<<TEXT
<input type="radio" {$value} name="_form[{$this->name}]" value="{$v}" />{$v}&nbsp;
TEXT;
			}
		}else{
			throw new Exception('This is not enum row');
		}
		return $inputList;
	}

	/**
	 * @return boolean
	 */
	public function isNull(){
		if($this->allowNull()===true){
			$name = $this->name;
			if($this->current->$name===null){
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
	}
}
